package com.huaxin.device.config;

import com.huaxin.device.common.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器：在请求开始时从 Header 初始化 UserContext，在结束时清除。
 */
@Component
public class UserContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // ✅ 在请求开始时初始化 UserContext
        UserContext.init();
        return true; // 继续执行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // ✅ 在请求结束时清除 ThreadLocal，防止内存泄漏
        UserContext.clear();
    }
}
